<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

include_once(APPPATH.'controllers/adminController.php');

class ObjectController extends AdminController {
	/**
	 * 子类自定义字段
	 */
	var $appname;					//应用名称
	var $workgroup;					//组
	var $modelName;					//默认model
	var $packet_group;				//列表页标签组
	var $detail_views;							//默认列表详细页标签组
	var $search_options;				//默认简单搜索项
	var $default_filter;					//默认查询过滤条件

	function __construct(){
		parent::__construct();
	}

	function link() {
		$url = $this->input->get('url');
		if(!$url) return;

		$wg = $this->input->get_post('wg');
        $data = array('url'=>$url);
        $this->page($wg, 'common/link',$data);
	}

	function render_finder(&$finder) {
		//finder
		$finder = $this->finder_common($finder);
		$ret = $this->diapatch_action($finder);
		if( ! $ret){
			//itemPage

			$itemPage = $this->finder_records($finder);			

			//渲染页面
			$this->render_pages($finder , $itemPage);
		}
	}
	
	function diapatch_action(&$finder){
		$action = $this->input->get_post('action');
		if($action=='packet') {
			$this->_packet($finder);
		}else if($action == 'filter') {
			$this->_filter($finder);
		}else if($action == 'filter2packet'){
			$this->_filter2packet($finder);
		}else if($action == 'packet_count'){
			$this->_packet_count($finder);
		}else{
			return false;		
		}
		return true;
	}
	
	function finder_common(&$finder){
		$_finder = $this->input->get_post('_finder');
		$finder = $this->_merge_array($finder,$_finder);
		if( ! isset($finder['finder_id'])){
			$finder['finder_id']=substr(md5(uri_string()),0,6);
		}
		$finder['workgroup'] = $this->_gVal($finder , 'workgroup' , $this->workgroup);
		$finder['appname'] = isset($finder['appname']) ? $finder['appname'] : $this->appname;
		$finder['controller'] = isset($finder['controller']) ? $finder['controller'] : strtolower(get_class($this));
		$finder['object_name'] =  isset($finder['modelName']) ? $finder['modelName'] : $this->modelName;
		$finder['search_options'] = $this->_gVal($finder , 'search_options' , $this->search_options);
		$finder['packet_group'] = $this->_gVal($finder , 'packet_group' , $this->packet_group);
		$finder['inputFilter'] = $this->input->get('filter');
		$finder['detailFunc'] = isset($finder['detailFunc']) ? $finder['detailFunc'] : 'finder_detail';
		$view = $this->input->get_post('view');
		$finder['view'] = $view ? $view : 0;
		$model = &$this->_load_model($finder['object_name']);
		$finder['select_name'] = $model->primary_key;
		$finder['allCols'] = $model->columns;
		$this->_findAllPacket($finder);
		return $finder;
	}

	/**
	 * 查找所有packet
	 */
	function _findAllPacket(&$finder){
		//获取用户定义的packets
		$user = $this->session->userdata('user');
		$this->load->model('desktop/admin_filter_model', 'filtermdl');
		$filters = $this->filtermdl->findFiltersByUserId($user['userId'] , $finder['finder_id']);
		
		if( ! isset($finder['packet_group'])){
			$finder['packet_group'] = array();
		}
		
		foreach($filters as $filter){
			$packet = array();
			$packet['label'] =  $filter['name'];
			$packet['filter_id'] = $filter['filter_id'];
			$packet['customize'] = true;
			$packet['filter'] = json_decode($filter['query'], true);
			$finder['packet_group'][] = $packet;
		}
	}
	
	//***********************执行查询***************************************
	function finder_records(&$finder){
		//解析列表项
		$cols = $this->input->get_post('cols');
		$cols = (empty($cols) && isset($finder['cols'])) ? $finder['cols'] : $cols;
		//解析搜索条件
		$filter = $this->input->get_post('filter');
		$filter = $this->_parseFilter($filter , $finder['object_name']);
		$df = isset($finder['filter']) ? $finder['filter'] : $this->default_filter;
		$filter =  $this->_merge_array($filter,$this->_parseFilter($df , $finder['object_name']));
		$filter =  $this->_merge_array($filter,$this->_parse_packet_filter($finder));
		//排序
		$orderby = $this->_parseOrderby();
		$orderby = $this->_gVal($finder , 'orderby' , $orderby);
		$itemPage = $this->_finder($finder['object_name'] , $cols, $filter, $orderby);
		$finder['finalFilter'] = array();
		if(is_array($filter)){
			foreach($filter as $item){
				$model = &$this->_load_model($finder['object_name']);
				$item[1]  = $model->consummateCol($item[1]);
				$finder['finalFilter'][] = $item;
			}	
		}
		return $itemPage;
	}

	function _finder($modelName , $clos, $filter, $orderby){
		$this->load->helper('finder');
		return finder($modelName, $clos, $filter, $orderby) ;
	}

	/*
	 * 列表页的标签组
	 */
	function _packet($finder) {
		//finder
		$data = array();
		$view = $this->input->get_post('view');
		$data['view'] = $view ? $view : 0;
		$modelName = $finder['object_name'];
		$model = &$this->_load_model($modelName);
		
		foreach($finder['packet_group'] as &$packet) {
			$filter = $this->_parseFilter($this->_gVal($finder,'filter') , $modelName);
			$filter = $this->_merge_array($filter , $this->_parseFilter($this->_gVal($packet,'filter') , $modelName));
			$filter =  $this->_merge_array($filter , $this->_parseFilter($finder['inputFilter'] , $modelName));
			if( ! (isset($finder['packet_async']) && $finder['packet_async'])){
				$cnt = $model->findCount($filter);			
				$packet['count'] = $cnt;
			}
		}
		
		$data['finder'] = $finder;
		$data['packet_group'] = $finder['packet_group'];
		$data['inputFilter'] = $finder['inputFilter'];
		$this->load->view('finder/_packet', $data);
	}
	
	/*
	 * 列表页标签组计数
	 */
	function _packet_count($finder) {
		$modelName = $finder['object_name'];
		$model = &$this->_load_model($modelName);
		$filter = $this->_parseFilter($this->_gVal($finder,'filter') , $modelName);
		$filter =  $this->_merge_array($filter,$this->_parse_packet_filter($finder));
		$filter =  $this->_merge_array($filter , $this->_parseFilter($finder['inputFilter'] , $modelName));
		$cnt = $model->findCount($filter);
		echo $cnt;
	}

	//***********************高级搜索***********************************	
	/*
	 * 高级搜索
	 */
	function _filter($finder) {
		$model = &$this->_load_model();
		$advancedFilterCols = $this->_gVal($finder , 'advancedFilterCols' , null);
		$allCols = $model->getFilterColumns($advancedFilterCols);
		$data = array();
		$data['allCols'] = $allCols;
		$data['modelName']=$this->modelName;
		$data['finder_id']=$this->input->get_post('finder_id');
		$this->load->view('finder/_filter', $data);
	}

	//***********************另存筛选条件***********************************	
	/*
	 * 另存筛选结果
	 */
	function _filter2packet($finder){
		$filterquery = $this->input->get_post('filterquery');
		$data = array();
		$data['filterquery'] = $filterquery;
		$data['finderId'] = $finder['finder_id'];
		$this->load->view('finder/_filter2packet',$data);
	}
	
	//***************************搜索***********************
	/*
	 * 合并数组
	 */
	function _merge_array($array1, $array2){
		if(is_array($array1)){
			if(is_array($array2)){

				return array_merge($array1,$array2);
			}else{
				return $array1;
			}
		}else{
			return $array2;
		}
	}

	/*
	 * 解析搜索条件
	 */
	function _parseFilter($filters , $modelName){
		if(!isset($filters) || !is_array($filters)){
			return null;
		}
		$result = array();
		foreach($filters as $field=>$filter){
			$model = $this->_load_model($modelName);
			$cols = $model->columns;
			$colDefine = null;
			if(isset($cols[$field])){
				$colDefine = $cols[$field];
			}

			//'field4'=> '123'
			if( ! is_array($filter)){
				$this->_parse2dbFilter($field, $colDefine, array('val'=>$filter) , $result);
			}else{
				/*
				 * 'field2'=>array(
				 * 		array('op'=>'>' , 'val'=>'123'),
				 * 		array('op'=>'<' , 'val'=>'456')
				 * 	)
				 */
				foreach($filter as $item){
					$this->_parse2dbFilter($field, $colDefine, $item , $result);
				}
			}
		}
		return $result;
	}

	/**
	 * 解析成model支持的filter格式
	 */
	function _parse2dbFilter($field, $colDef, $item, &$dbfilter){
		if( ! array_key_exists('val' , $item)){
			return;
		}
		if(isset($item["op"])){
			$op = $item["op"];
		}elseif( (isset($colDef['like']) && $colDef['like'] == TRUE) ){
			$op = 'LIKE';
		}else{
			$op = '=';
		}
		
		//日期格式要特殊处理, =转换为> + <
		if($op == "=" && isset($colDef['type']) && $colDef['type'] == "date"){
			$dbf1 = array('>=' , $field);
			$dbf2 = array('<=' , $field);
			$value = $item["val"];
			if(is_array($value) && count($value) >= 3){
				$v1 = $value;
				$v2 = $value;
				$v1['second'] = '00';
				$v2['second'] = '59';
				if($value['minute'] == '00'){
					$v1['minute'] = '00';
					$v2['minute'] = '59';
					if($value['hour'] == '00'){
						$v1['hour'] = '00';
						$v2['hour'] = '23';
					}
				}
				$v1 = $v1['date'].' '.$v1['hour'].':'.$v1['minute'].':'.$v1['second'];
				$v2 = $v2['date'].' '.$v2['hour'].':'.$v2['minute'].':'.$v2['second'];
			}elseif(!is_array($value)){
				$v1 = $v1['date'].' '.'00:00:00';
				$v2 = $v2['date'].' '.'23:59:59';
			}
			$dbf1[] = $v1;
			$dbf2[] = $v2;
			$dbfilter[] = $dbf1;
			$dbfilter[] = $dbf2;
		}else{
			$value = $this->_parseValue($item["val"],$colDef);
			$dbfilter[] = array($op,$field,$value);		
		}
	}
	
	/**
	 * 解析value
	 */
	function _parseValue($value,$colDefine){
		if(is_string($value)){
			$value = trim($value);
		}
		if(!$colDefine || !isset($colDefine['type'])){
			return $value;
		}

		if($colDefine['type'] == "date"){
			if(is_array($value) && count($value) == 3){
				$value = $value['date'].' '.$value['hour'].':'.$value['minute'].':00';
			}
		}else if($colDefine['type'] == "bool"){
			if($value == 'true' || $value === true){
				$value = 'true';
			}else if($value == 'false' || $value === false){
				$value = 'false';
			}
		}
		return $value;
	}

	function _parse_packet_filter($finder){
		$view = $this->_gVal($finder , 'view' , 0);
		if(isset($finder['packet_group']) && is_array($finder['packet_group']) && count($finder['packet_group']) > $view){
			$group = $finder['packet_group'][$view];
			if(isset($group['filter'])){
				return $this->_parseFilter($group['filter'] , $finder['object_name']);
			}
			return null;
		}
	}


	//***********************排序****************************************
	function _parseOrderBy(){
		$orderby = null;
		$_finder = $this->input->get_post('_finder');
		if(!empty($_finder['orderBy']) && !empty($_finder['orderType'])) {
			$orderby = array($_finder['orderBy']=>$_finder['orderType']);
		}
		return $orderby;
	}

	//***********************页面加载***********************************
	/*
	 * 加载页面
	 */
	function render_pages(&$finder , $itemPage = null){
		$data = array();
		$data['finder'] = &$finder;
		$finder['itemPage'] = $itemPage;
		

		//渲染设置了view的action
		if(isset($finder['actions'])){
			foreach($finder['actions'] as $key=>$action){
				if(isset($action['func']) && exist_method($this,$action['func'])){
					$this->$func($finder);
					unset($finder['actions'][$key]);
				}
				if(isset($action['view'])){
					$page = $this->load->view($action['view'], $data, true);
					$finder['views']['actions'] = $page;
					unset($finder['actions'][$key]);
				}
			}
		}


		//默认页面
		$part_views = array(
			'innerheader' => 'finder/innerheader',
			'pager' => 'finder/pager',
			'list' => 'finder/list',
			'mainhead' => 'finder/main_head',
			'mainfoot' => 'finder/main_foot'
		);

		//自定义页面
		if(isset($finder['part_views'])){
			foreach($finder['part_views'] as $k=>$v){
				if(isset($part_views[$k])){
					$part_views[$k] = $v;
				}
			}
		}

		$_finder = $this->input->get_post('_finder');
		if(isset($_finder['finder_id'])){
			//有finder_id时只加载pager 和 innerheader
			$this->part_view('.innerheader',$part_views['innerheader'], $data);
			$this->part_view('.pager',$part_views['pager'], $data);
		}else{
			//一般情况下加载
			$finder['views']['innerheader'] = $this->load->view($part_views['innerheader'],$data,true);
			$finder['views']['pager'] = $this->load->view($part_views['pager'],$data,true);
			$this->part_view('.mainHead',$part_views['mainhead'], $data);
			$this->part_view('.mainFoot',$part_views['mainfoot'],$data);
		}

		$this->page($finder['workgroup'], $part_views['list'], $data);
	}

	function render_list(&$finder , $itemPage = null){
		$data = array();
		$data['finder'] = &$finder;
		$finder['itemPage'] = $itemPage;
		$this->load->view($part_views['list'], $data);
	}
		
	//***********************详细页面***********************************	
	/*
	 * 详细信息页面
	 */
	function finder_detail($finderview = null , $uriString = null){	
		$this->render_detail_tabs($this->detail_views , $finderview, $uriString);
		$this->reder_detail_page($this->detail_views , $finderview);
	}
	
	/*
	 * 渲染详细页标签组
	 */
	function render_detail_tabs($detail_views , $finderview = null , $uriString = null){
		$data = array();
		if( ! $finderview){
			$finderview = $this->input->get_post('finderview');		
		}
		if( ! $uriString){
			$data['uriString'] = uri_string();
		}else{
			$data['uriString'] = $uriString;					
		}
		$data['id'] = $this->input->get_post('id');
		$data['finder_id'] = $this->input->get_post('finder_id');
		$data['detail_views'] = $detail_views ;
		if( ! $finderview || $finderview == 'default'){
			$data['finderview']  = $this->_find_default_view($detail_views);
		}else{
			$data['finderview'] = $finderview;
		}
		$this->load->view('finder/_detail_tabs', $data);
	}
	
	/*
	 * 执行回调渲染详细页面
	 */
	function reder_detail_page($detail_views , $finderview = null){
		if( ! $finderview){
			$finderview = $this->input->get_post('finderview');		
		}
		$viewDefine = $this->_getViewDef($detail_views , $finderview);
		if(empty($viewDefine) || !isset($viewDefine['func']) || !method_exists($this, $viewDefine['func'])){
			return;
		}
		$func = $viewDefine['func'];
		$this->$func();
	}
	
	/*
	 * 获取详细页的视图定义
	 */
	function _getViewDef($detail_views , $finderview){
		if(empty($detail_views)){
			return null;
		}
		if(!isset($detail_views[$finderview])){
			return $detail_views[$this->_find_default_view($detail_views)];
		}
		return $detail_views[$finderview];
	}

	/*
	 * 默认详细页视图
	 */
	function _find_default_view($detail_views){
		if($detail_views){
			foreach($detail_views as $k=>$view){
				if(isset($view['default']) && $view['default']){
					return $k;
				}
			}
		}
		return null;
	}
	
	//***********************垃圾桶***********************************	
	function recycleIndex(){
		$finder = array(
			'name'=>'recycle',
			'title'=>'垃圾桶',
			'buildinclean'=>true,
			'buildinactive'=>true,
			'buildinindex'=>true,
			'filter'=>array('disabled'=>'true')
		);
		$this->render_finder($finder);
	}

	/*
	 * 删除到垃圾桶
	 */
	function recycle(){
		$model = &$this->_load_model();
		$ids = $this->input->get_post($model->primary_key);
		$ret = $model->disable($ids);
		if($ret){
			$this->out_put_jcmd($ret,'选定记录删入垃圾桶');
		}else{
			$this->out_put_jcmd($ret,'选定记录无法删入垃圾桶');
		}
	}

	/*
	 * 从垃圾桶清除
	 */
	function delete(){
		$model = &$this->_load_model();
		$ids = $this->input->get_post($model->primary_key);
		$ret = $model->delete($ids);
		if($ret){
			$this->out_put_jcmd($ret,'选定记录已删除成功!');
		}else{
			$this->out_put_jcmd($ret,'选定记录无法删除!');
		}
	}

	/**
	 * 从垃圾桶还原
	 */
	function active(){
		$model = &$this->_load_model();
		$ids = $this->input->get_post($model->primary_key);
		$ret = $model->active($ids);
		if($ret){
			$this->out_put_jcmd($ret,'选定记录已从垃圾桶恢复!');
		}else{
			$this->out_put_jcmd($ret,'选定记录无法从垃圾桶恢复!');
		}
	}


	//***********************公用方法***********************************	
	function _gVal($collection , $key , $defaultValue = null){
		if( ! isset($collection[$key])){
				return $defaultValue;
		}
		if(empty($collection[$key])){
			return $defaultValue;
		}
		return $collection[$key];
	}
	
	/*
	 * 加载model
	 */
	function _load_model($modelName=null){
		if(!$modelName){
			$modelName = $this->modelName;
		}
		$this->load->model($modelName, 'model');
		return $this->model;
	}

	function page($wg,$view,$vars=array()) {
		$vars['workground'] = $wg;
		if( ! empty($wg) ){
			$this->renderBreadcrumbs($wg);
		}
		$curWg = $this->input->get_request_header('Workground');
		$wg = !$wg?$curWg:$wg;//is wg is null, wg = curWg
	
		if($wg != $curWg) {
			$this->load->model('admin_profile_model');
			$sideMenu = $this->admin_profile_model->getSidemenu($wg);
			$vars['_side_menu'] = $sideMenu;
			$this->part_view('.side-content','desktop/sidemenu',$vars);
			echo '<script>window.currentWorkground="'.$wg.'";</script>';
		}
		$this->load->view($view, $vars);
	}

	function renderBreadcrumbs($wg){
		$this->load->model('admin_profile_model');
		$mainMeanu = $this->admin_profile_model->getMenu();
		$vars['mainMid'] = 0;
		if(isset($mainMeanu[$wg])){
			$vars['mainMid'] = $mainMeanu[$wg]['mid'];
		}
		$sideMenu = $this->admin_profile_model->getSidemenu($wg);
		$vars['subMid'] = 0;
		//TODO:这里只进行了简单处理
		if( ! empty($sideMenu['children'])){
			foreach($sideMenu['children'] as $idx=>$subMenu){
				foreach($subMenu['children'] as $idx1=>$item){
					if(ltrim($item['link'] , '/?') == ltrim($this->input->server('REQUEST_URI') , '/?')){
						$vars['subMid'] = $vars['mainMid'].$idx.$idx1;
						break;
					}
				}
			}
		}
		//通过workground和viewName来获取面包屑的mid:mid, viewName => viewMenuDefinition{mid}
		$this->load->view('page/breadcrumbs', $vars);
	}
	
	function part_view($viewName, $view, $vars=array(), $return = FALSE) {
		$html = '<!-----'.$viewName.'-----';

		$html .= $this->load->view($view, $vars, TRUE);
		$html .= '-----'.$viewName.'----->';

		if(!$return) {
			echo $html;
		} else {
			return $html;
		}
	}

	function upload_splash(){
		$this->output->set_header('Content-Type: text/jcmd; charset=utf-8');
		$ret = $this->input->get_post('ret');
		echo $ret;
	}

	/*
	 * 通用jcmd消息返回
	 * $succ  操作是否成功
	 * $redirect 跳转页
	 * $msg 默认消息
	 */
	function out_put_jcmd($succ, $msg=null, $redirect=null , $data=null){
		$result = array();
		if($succ){
			$result['success'] = $msg ? $msg : '操作成功';
		}else{
			$result['error'] = $msg ? $msg : '操作失败';
		}
		$result['redirect'] = $redirect;
		if( ! empty($data)){
			$result['data'] = $data;			
		}
		$this->output->set_header('Content-Type: text/jcmd; charset=utf-8');
		$this->output->set_header('Cache-Control: no-cache');
		echo json_encode($result);
	}
}
?>
